var express = require('express');
var router = express.Router();

//导入模型对象
const CateModel = require('../models')['Cate']
const NewsModel = require('../models')['New']

//导入事件日期处理模块
const moment=require('moment')

//载入自动验证表单数据的模块
const expressJoi = require('@escook/express-joi')
//载入验证模块
const {
    news_add_schema,
    news_list_schema
} = require('../schema/news')

//新闻添加表单
router.get('/news/create', async (req, res) => {
    //查询出新闻分类数据
    const cateData = await CateModel.findAll();
    res.render('news/news_add.html', {
        cateData
    })
})

//新闻添加入库
router.post('/news', expressJoi(news_add_schema), async (req, res) => {
    try {
        //增补2个数据
        req.body.createdAt = new Date()
        req.body.updatedAt = new Date()
        const data = await NewsModel.create(req.body)
        if (data) {
            res.cc(201, '添加新闻成功', data)
        } else {
            res.cc(400, '添加新闻失败')
        }
    } catch (e) {
        res.cc(400, e.message)
    }
})

//新闻列表展示
router.get('/news', (req, res) => {
    res.render('news/news_list.html')
})

//新闻数据获取
router.get('/news/newsList', expressJoi(news_list_schema), async (req, res) => {
    try {

        //接收页码
        let page = req.query.page || 1
        //接收每页显示的条数
        let limit = parseInt(req.query.limit) || 5
        //计算偏移量
        let offset=(page-1)*limit

        const {
            count,
            rows
        } = await NewsModel.findAndCountAll({
            attributes: ['id','title', 'img_url', 'author', 'view_nums', 'cateId', 'createdAt', 'updatedAt', 'Cate.cate_name'],
            include: [CateModel],
            order: [
                ['createdAt', 'DESC']
            ],
            offset,
            limit
        })

        //对数据进行处理，方便前端进行数据的渲染
        let arr=[]
        rows.forEach(item=>{
            console.log(item);
            item.dataValues.img_url = `<img src='${item.dataValues.img_url}' width='80' height='50'>`;
            item.dataValues.createdAt = moment(
              item.dataValues.createdAt
            ).format("YYYY-MM-DD HH:mm:ss");
            item.dataValues.updatedAt = moment(
              item.dataValues.updatedAt
            ).format("YYYY-MM-DD HH:mm:ss");
            arr.push(item)
        })
       

        //返回数据
        res.json({
            code: 0,
            msg: '',
            count,
            data: arr
        })

    } catch (e) {
        res.send(e.message)
    }

})



module.exports = router